package cn.tedu.fruitshop.service.impl;

import cn.tedu.fruitshop.ex.ServiceException;
import cn.tedu.fruitshop.mapper.CouponsMapper;
import cn.tedu.fruitshop.pojo.dto.CouponsAddNewDTO;
import cn.tedu.fruitshop.pojo.entity.Coupons;
import cn.tedu.fruitshop.pojo.vo.CouponsListItemVO;
import cn.tedu.fruitshop.service.CouponsService;
import cn.tedu.fruitshop.web.ServiceCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author www
 * @create 2022-11-11 21:43
 */
@Slf4j
@Service
public class CouponsServiceImpl implements CouponsService {

    @Autowired
    CouponsMapper couponsMapper;

    @Override
    public void add(CouponsAddNewDTO couponsAddNewDTO) {
        log.debug("开始执行添加优惠券的操作，参数:{}",couponsAddNewDTO);
        log.debug("查询是否存在这个优惠券");
        int rows = couponsMapper.getStandardByName(couponsAddNewDTO.getCouponName());
        if (0 < rows){
            String message = "该优惠券已经存在，添加失败";
            log.debug("{}",message);
            throw new ServiceException(ServiceCode.ERR_CONFLICT,message);
        }

        Coupons coupons = new Coupons();
        BeanUtils.copyProperties(couponsAddNewDTO,coupons);
        log.debug("不存在，开始添加，{}",coupons);
        rows = couponsMapper.insert(coupons);
        if (1 != rows){
            String message = "添加失败,服务器繁忙，请稍后再试";
            log.debug("{}",message);
            throw new ServiceException(ServiceCode.ERR_INSERT,message);
        }
    }

    @Override
    public void deleteByCouponName(String couponName) {
        log.debug("开始执行【根据title删除优惠券】的操作，参数:{}",couponName);
        log.debug("查询是否存在这个优惠券");
        int rows = couponsMapper.getStandardByName(couponName);
        if (0 == rows){
            String message = "该优惠券不存在，删除失败";
            log.debug("{}",message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND,message);
        }
        log.debug("存在，开始删除，{}",couponName);
        rows = couponsMapper.deleteByCouponName(couponName);
        if (1 != rows){
            String message = "删除失败,服务器繁忙，请稍后再试";
            log.debug("{}",message);
            throw new ServiceException(ServiceCode.ERR_INSERT,message);
        }
    }

    @Override
    public List<CouponsListItemVO> list() {
        log.debug("开始查询优惠券列表：无参");
        List<CouponsListItemVO> list = couponsMapper.list();
        return list;
    }
}
